<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>JSON对象</h1>
<hr>
<script>

    //1.JSON基本语法
    /*
    let p = {"name": "张三丰", "age": 60};
    let persons = [
        p,
        {"name": "张无忌", "age": 45},
        {"name": "风清扬", "age": 70},
        {"name": "东方不败", "age": 30}
    ];
    console.log(p);
    console.log(persons);*/

    //2.json转字符串
    /*
    let p = {"name": "张三丰", "age": 60, "gender": "男", "addr": "湖北省武当山"};
    let persons = [
        p,
        {"name": "张无忌", "age": 45, "gender": "男", "addr": "湖北省武当山"},
        {"name": "风清扬", "age": 70, "gender": "男", "addr": "陕西省华山"},
        {"name": "东方不败", "age": 30, "gender": "男", "addr": "黑木崖"}
    ];
    console.log(JSON.stringify(p));
    console.log(JSON.stringify(p, ["name", "gender"]));
    console.log(JSON.stringify(persons));
    console.log(JSON.stringify(persons, ["name", "age"]));
    console.log(JSON.stringify(persons, ["name", "age"], "\r "));
    */


    //3.字符串转json

    let dog = '{"alias":"二郎犬","type":"神犬","color":"黑色","age":1000,"weight":50}';
    let json = JSON.parse(dog)
    console.log(typeof (json));
    console.log(json);

    //4.json对象数组的CRUD

    let persons = [
        {"pid": "0001", "name": "张三丰", "age": 60},
        {"pid": "0002", "name": "张无忌", "age": 45},
        {"pid": "0003", "name": "风清扬", "age": 70},
        {"pid": "0004", "name": "东方不败", "age": 30}
    ]

    //1.遍历
    persons.forEach(function (e, index) {
        console.log("第" + (index) + "个元素是：" + JSON.stringify(e));
    })
    //2.添加新元素
    persons.push({"pid": "0005", "name": "郭靖", "age": 35});
    console.log("-------添加新元素之后------");
    persons.forEach(function (e, index) {
        console.log("第" + (index) + "个元素是：" + JSON.stringify(e));
    })
    //3.修改pid=3元素的名字属性
    persons.forEach(function (e, index) {
        if (e.pid == 3) {
            e.name = "黄老邪";
            return;
        }
    });
    console.log("-------修改姓名之后------");
    persons.forEach(function (e, index) {
        console.log("第" + (index) + "个元素是：" + JSON.stringify(e));
    })

    //4.删除所有姓'张'的元素

    for (let index = 0; index < persons.length; index++) {
        if (persons[index].name.startsWith('张')) {
            persons.splice(index, 1);
            index--; //注意下标向前移动一次。
        }
    }
    ;
    //或者从后向前循环。
    /*
    for (let index = persons.length-1; index >= 0; index--) {
        if (persons[index].name.startsWith('张')) {
            persons.splice(index, 1);
        }
    };*/
    /*
    persons.forEach(function(e,index){
        if (e.name.startsWith('张')) {
            persons.splice(index, 1);
            index--; //错误，forEach是只读的。并不能利用这种语句改变数组所存储的元素。
        }
    })*/

    console.log("-------删除姓'张'元素之后------");
    persons.forEach(function (e, index) {
        console.log("第" + (index) + "个元素是：" + JSON.stringify(e));
    })


</script>
</body>
</html>